<template>
  <el-upload
    action="#"
    :auto-upload="false"
    :multiple="true"
    :limit="limit"
    :on-change="handleChange"
    :on-exceed="handleExceed"
    :file-list="fileList"
  >
    <t-button className="uploadClass" svgIcon="ic-upload">点击上传</t-button>
    <div slot="tip" class="el-upload__tip text-[12px] text-[#7E8A9D]">
      <span v-if="accept.length">支持上传{{ accept.join("、") }}等格式且不大于100M，最多可上传{{ limit }}个附件</span>
      <span v-else>最多可上传{{ limit }}个附件，每个附件限制100MB以下，格式不限</span>
    </div>
    <div slot="file" slot-scope="{ file }">
      <div class="flex flex-row items-center">
        <span class="el-icon-success mr-[4px]" style="color: #078d5c"></span>
        <span class="mr-[4px] h-[8px] w-[1px] bg-[#E8EAEF]"></span>
        <img :src="require(`@/assets/images/${getIconByFile(file?.name)}.svg`)" />
        <div class="ml-[8px] flex-1 leading-[24px]">{{ file.name }}</div>
        <SvgIcon name="file_delete" class="mr-[8px] cursor-pointer text-[16px]" @click="handleRemove(file)" />
      </div>
    </div>
  </el-upload>
</template>

<script>
import fileIcon from "@/mixin/fileIcon";
/**
 * 文件不自动上传组件，只返回文件集合
 */
export default {
  name: "FileUploadUn",
  mixins: [fileIcon],
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      },
    },
    limit: {
      type: Number,
      default: 10,
    },
    /**
     * 接受文件类型，默认所有类型
     * 例如 ['jpg', 'png']
     */
    accept: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      // 文件列表
      fileList: [],
    };
  },
  methods: {
    // 文件超出个数限制时
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`,
      );
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((item) => {
        return item.uid !== file.uid;
      });
      this.onChange();
    },
    // 文件改变时校验文档大小
    handleChange(file, fileList) {
      if (file.size <= 0) {
        this.$message.warning(`文件为空，无法继续上传`);
      }
      if (file.size / 1024 / 1024 > 100) {
        this.$message.warning(`文件 ${file.name} 大小超过 100MB，无法继续上传`);
      }
      const list = fileList.filter((item) => {
        return item.size > 0 && item.size / 1024 / 1024 <= 100;
      });
      this.fileList = list;
      this.onChange();
    },
    onChange() {
      this.$emit("change", this.fileList);
    },
  },
};
</script>

<style></style>
